package com.example.controller;

import com.example.entity.BaseResponse;
import com.example.entity.ProductEntity;
import com.example.entity.ProductSearchEntity;
import com.example.entity.ResultBody;
import com.example.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class ProductController {
    @Autowired
    ProductService productService;

    @RequestMapping("/getProduct")
    public ProductEntity getTask(int id) {
        return new ProductEntity();
    }

    /**
     * 列出所有产品信息
     *
     * @return 产品信息列表的封装对象
     */
    @RequestMapping("/listProduct")
    @CrossOrigin(origins = "*", allowedHeaders = "*")
    public BaseResponse<ProductEntity> listTask() {
        List<ProductEntity> productList = productService.findAll();
        return new BaseResponse<ProductEntity>(0, "success",
                productList.size(), productList);
    }

    /**
     * 保存设备信息
     *
     * @param method 产品保存方法，可选值为"添加"或"修改"
     * @param productEntity 产品信息实体类
     * @return 返回操作结果的封装对象
     */
    @RequestMapping("/saveProduct")
    @ResponseBody
    @CrossOrigin(origins = "*", allowedHeaders = "*")
    public ResultBody saveProduct(String method, ProductEntity productEntity){
        System.out.println("修改修改修改");
        System.out.println(productEntity.toString());
        System.out.println(method);
        if (productService.saveProduct(method,productEntity)){
            return new ResultBody(0, "success");
        } else{
            return new ResultBody(1, "fail");
        }
    }

    /**
     * 删除产品信息
     *
     * @param id 产品ID
     * @return 返回操作结果的封装对象
     */
    @RequestMapping("/deleteProduct")
    @ResponseBody
    @CrossOrigin(origins = "*", allowedHeaders = "*")
    public ResultBody deleteProduct(int id){
        if (productService.deleteProduct(id)){
            return new ResultBody(0, "success");
        } else{
            return new ResultBody(1, "fail");
        }
    }

    /**
     * 查询产品信息
     *
     * @param productSearch 查询条件实体类
     * @return 产品信息列表的封装对象
     */
    @RequestMapping("/productSearch")
    @ResponseBody
    @CrossOrigin(origins = "*", allowedHeaders = "*")
    public BaseResponse<ProductEntity> productSearch(ProductSearchEntity productSearch) {
        System.out.println(productSearch);
        productSearch.setStart((productSearch.getPage()-1)*productSearch.getLimit());
        List<ProductEntity> equipmentList = productService.productSearch(productSearch);
        return new BaseResponse<ProductEntity>(0, "success",
                productService.productSearchCount(productSearch), equipmentList);
    }
}
